<?php
namespace app\mobile\controller;

use think\Db;
use think\Cache;
use think\Request;
use think\Session;
use think\Exception;
use app\mobile\model\Shop;
use app\mobile\model\MemberCoupon;
use app\mobile\model\MemberRefund;
use app\mobile\model\MemberIntegral;
use app\mobile\model\MemberBrokerage;
use app\mobile\model\MemberDistribution;
use app\mobile\model\MemberOrderAttached;
use app\mobile\model\MemberDistributionOrder;

/**
 * Class MemberOrder
 * @package app\mobile\controller   涉及订单
 */
class MemberOrder extends BaseController
{
    /*
     * 我的分销->分销商
     */
    public function my_distribution(Request $request)
    {
        $id = Session::get('member_id');   //会员id(分销人)

        $model = new MemberDistribution();

        $level = MemberDistribution::where('referrals_id', $id)->value('level');   //查找此会员的级别定位

        //老板登录
        if (Session::get('member_id') == 1) {
            $level = 1;
        }

        // 级别数量
        $rank['one_level'] = $model
            ->where(['hierarchy' => ['like', '%,' . $id . ',%'], 'level' => $level + 1])
            ->with('member')//(下线人)匹配会员表
            ->count();


        $rank['two_level'] = $model
            ->where(['hierarchy' => ['like', '%,' . $id . ',%'], 'level' => $level + 2])
            ->with('member')//(下线人)匹配会员表
            ->count();

        if ($request->isPost()) {
            $page = $request->post('page');
            $level_float = $request->param('level');   //层级浮动值
            $level += $level_float;

            if (Session::get('member_id') == 1) {
                $level -= 1;
            } //老板登录 层级降1

            // 搜索条件
            $condition['sun_member_distribution.hierarchy'] = ['like', '%,' . Session::get('member_id') . ',%'];

            // 条件
            if (!empty($level)) $condition['sun_member_distribution.level'] = ['eq', $level];
            $query = $model
                ->where($condition)
                ->with([
                    'member',
                    'memberDistributionOrder' => function ($e) {
                        $e->where(['distribution_id' => Session::get('member_id')]);
                    },
                    'TjMember'
                ])
                ->limit(($page - 1) * 6, 6)
                ->order('create_time desc')
                ->select();

            //整理佣金
            $result['data'] = [];

            if ($query) {
                foreach ($query as $key => &$value) {
                    $result['data'][$key]['avatar'] = $value->member->avatar;  //分销商头像
                    $result['data'][$key]['nickname'] = $value->member->nickname;   //分销商昵称
                    $result['data'][$key]['username'] = $value->member->username;   //手机号
                    $result['data'][$key]['TjNickname'] = $value->tjMember->nickname;   //分销商上级昵称
                    $result['data'][$key]['create_time'] = $value->create_time;  //成为分销商的时间
                    $result['data'][$key]['brokerage'] = "0.00";  //分销佣金初始化
                    //分销订单
                    if ($value->memberDistributionOrder) {
                        foreach ($value->memberDistributionOrder as $item) {
                            $item->memberOrder;   //拓展符合条件的会员订单
                        }
                        //                        return json($query);
                        //整理佣金
                        foreach ($value->memberDistributionOrder as $k => $_item) {
                            if (!is_null($_item->memberOrder)) {   //合计有订单数据的佣金
                                $result['data'][$key]['brokerage'] += $_item['brokerage'];
                            }
                        }
                    }
                }
            }
            $result['pages'] = ceil($model
                    ->where($condition)
                    ->with('member,memberDistributionOrder,TjMember')
                    ->count() / 6);

            return json($result);

        }
        return $this->fetch('', [
            'rank'         => $rank,
            'member_level' => $level,
        ]);
    }

    /*
     * 分销订单  (下级分销订单)
     */
    public function fx_order(Request $request)
    {
        //交易状态
        $status = [
            '交易中订单&nbsp;',
            '已完成订单&nbsp;',
        ];
        //查看用户当前层级 (用于查找下2级分润会员)
        $level = (new MemberDistribution)->where('referrals_id', Session::get('member_id'))->value('level');

        if ($request->isPost()) {

            //接收到的post数据
            $data = $request->post();

            //所有下级分销商
            $all = (new MemberDistribution())
                ->where([
                    'sun_member_distribution.level'     => ['elt', ($level + 2)],
                    'sun_member_distribution.hierarchy' => ['like', '%,' . Session::get('member_id') . ',%']
                ])->column('referrals_id');

            $model = new MemberDistributionOrder();
            //会员经验

            $result['data'] = $model
                ->where([
                    'sun_member_distribution_order.member_id'       => ['in', implode(',', $all)],
                    'sun_member_distribution_order.distribution_id' => Session::get('member_id'),
                    //必须是当前会员关联的订单
                ])->with(['memberDistribution', 'memberOrderList' => function ($e) {
                    //订单状态
                    $condition = ['status' => ['in', '3,4']];
                    $type = Request::instance()->post('type', 0);
                    if ($type == 0) {
                        //交易中的订单
                        $condition = ['status' => ['in', '0,1,2']];
                        //                        $condition = ['status' => ['in' , '0,1,2,3,4']];
                    }
                    $e->where($condition)->withField('id,status,price,shop_order_number,create_time,freight');

                }])->limit(($data['page'] - 1) * 10, 10)->order('brokerage desc')->select();

            if ($result['data']) {
                //会员表
                foreach ($result['data'] as &$value) {
                    if ($value->memberOrderList) {
                        $value->memberOrderList->total_price = bcadd($value->memberOrderList->freight, $value->memberOrderList->price, 2);
                    }
                    $value->memberDistribution->member->withField('id,avatar,nickname,suffer');

                }
            }

            $result['pages'] = ceil($model
                    ->where([
                        'sun_member_distribution_order.member_id'       => ['in', implode(',', $all)],
                        'sun_member_distribution_order.distribution_id' => Session::get('member_id'),  //必须是当前会员关联的订单
                    ])
                    ->with(['memberDistribution', 'memberOrderList' => function ($e) {
                        //订单状态
                        $condition = ['status' => ['in', '3,4']];
                        $type = Request::instance()->post('type', 0);
                        if ($type == 0) {    //交易中的订单
                            $condition = ['status' => ['in', '0,1,2']];
                            //                            $condition = ['status' => ['in' , '0,1,2,3,4']];
                        }
                        $e
                            ->where($condition)
                            ->withField('id,status,price,shop_order_number,create_time,freight');
                    }])
                    ->count() / 10);
            return json($result);
        }
        return $this->fetch('', [
            'statusList' => $status,
        ]);
    }

    /*
     * 取消订单
     */
    public function cancel(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->post();
            Db::startTrans();
            try {
                //改变主表订单状态
                Db::name('member_order')->where(['member_id' => Session::get('member_id'), 'shop_order_number' => $data['number']])->update(['status' => 5]);

                // 读取特价商品
                $limited = Db::name('member_order_attached')
                    ->where(['shop_order_number' => $data['number'], 'limited_status' => '1'])
                    ->field('number,goods_id')
                    ->select();

                // 特价商品更改回数量
                if ($limited) {
                    foreach ($limited as $value) {

                        Db::name('limited')->where(['goods_id' => $value['goods_id']])->setDec('purchase_number', $value['number']);

                    }
                }

                // 读取价格
                $brokerage = Db::name('member_distribution_order')->where(['order_number' => $data['number'], 'member_id' => Session::get('member_id')])->value('brokerage');

                if ($brokerage) {
                    // 更改金额参数
                    $distribution = Db::name('member_distribution_order')->where('order_number', $data['number'])->select();

                    foreach ($distribution as $value) {
                        Db::name('member_brokerage')->where('member_id', $value['distribution_id'])->setDec('to_yield', $value['brokerage']);
                        Db::name('member_brokerage')->where('member_id', $value['distribution_id'])->setDec('general_income', $value['brokerage']);
                    }

                    Db::name('member_distribution_order')->where('order_number', $data['number'])->delete();

                }


                // 删除分销订单
                Db::name('member_distribution_order')->where(['distribution_id' => $data['shop_id'], 'order_number' => $data['number'], 'member_id' => Session::get('member_id')])->delete();

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '取消订单成功'];
            } catch (\Exception $e) {
                Db::rollback();
                return ['code' => 400, 'message' => '网络繁忙,请重试'];
            }
        }
    }

    /*
     * 用户端 - 商品评价
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     * @param  string $goods_id         商品ID
     * @param  string $content          评论内容
     * @param  string $grade            星数
     * @param  string $attr             商品属性
     * @param  string $picArr           评论组图
     */
    public function goods_evaluate($order_id)
    {
        // 判断订单ID不存在
        if (!$order_id || !Session::get('member_id')) {
            throw new \Exception('无效操作');
        };
        $model = new MemberOrderAttached();
        //查找商品信息
        $goods_info = $model->where('id', $order_id)->field('id,order_number,shop_order_number,thumb_img,goods_id')->find();
        if (Request::instance()->isPost()) {
            // 获取参数
            $data = Request::instance()->param();
            $picArr = Request::instance()->param('picArr/a', '');

            // 判断是否上传图片
            if ($picArr[0]) {
                $picArr = array_map(function ($item) {
                    $item = ['path' => $item];
                    return $item;
                }, $picArr);
            }else{
                $picArr = "";
            }
            //查找商品信息
            $info = $model->where(['sun_member_order_attached.id' => $data['order_id']])->with('memberOrder')->find();

            // 启动事务
            Db::startTrans();
            try {

                // 判断是否提交过
                $find = Db::name('member_order_attached')
                    ->where(['goods_id' => $info['goods_id'], 'shop_order_number' => $info['shop_order_number'], 'status' => '1'])
                    ->value('title');

                if (!empty($find)) return ['code' => 402, 'message' => '该商品已评价,请勿重复评价'];

                if (!empty($picArr)) $picArr = serialize($picArr);


                $information = [
                    'member_id'   => Session::get('member_id'),
                    'shop_id'     => $info->memberOrder->shop_id,
                    'goods_id'    => $info['goods_id'],
                    'content'     => $data['content'],
                    'grade'       => $data['grade'],
                    'title'       => $info['title'],
                    'attr'        => $info['attr'],
                    'thumb_img'   => $info['thumb_img'],
                    'picArr'      => $picArr,
                    'create_time' => time()
                ];

                // 添加到评论表
                Db::name('shop_goods_evaluate')->insert($information);

                // 更改信息
                Db::name('member_order_attached')
                    ->where(['id' => $data['order_id'], 'status' => '2'])
                    ->update(['status' => '1']);

                // 增长评论数
                Db::name('shop_goods')->where(['id' => $info['goods_id']])->setInc('evaluate_number');

                // 送积分
                // Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', Cache::get('web_integral_evaluate_goods'));

                // 添加记录
                // Db::name('integral_record')->insert(
                //     [
                //         'member_id'   => Session::get('member_id'),
                //         'type_id'     => '1',
                //         'type'        => '购买',
                //         'integral'    => Cache::get('web_integral_evaluate_goods'),
                //         'title'       => '评价商品' . $find,
                //         'create_time' => time()
                //     ]
                // );

                // 查询是否还有
                $status = Db::name('member_order_attached')
                    ->where(['shop_order_number' => $info['shop_order_number'], 'status' => '2'])
                    ->select();

                // 更改主表
                if (empty($status)) {   //全部评价则此店铺主订单完结
                    Db::name('member_order')
                        ->where(['shop_order_number' => $info['shop_order_number'], 'member_id' => Session::get('member_id')])
                        ->update(['status' => '4']);
                }

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '评价商品成功,正在跳转...'];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙,请重试'];
            }
        }
        return $this->fetch('', [
            'goods_info' => $goods_info,
        ]);

    }

    /*
     * 查看物流
     */
    public function refund_details()
    {
        //获取订单店铺&商品&物流信息
        $order_id = Request::instance()->param('order_id');
        $express_info = (new \app\mobile\model\MemberOrder())->where('id', $order_id)->with('memberOrderAttached,shop')->find();

        if (!$express_info['express_number'] || !$express_info['express_value']) {
            return ['code' => 400, 'message' => '暂未发布物流信息'];
        };

        // 快递100
        $data['customer'] = Cache::get('web_express_customer');
        $data['param'] = json_encode(['com' => $express_info['express_value'], 'num' => $express_info['express_number']]);
        $data["sign"] = strtoupper(md5($data['param'] . Cache::get('web_express_key') . $data['customer']));

        $information = $this->express_post($data, Cache::get('web_express_url'));

        if (!$information['data']) {
            return ['code' => 400, 'message' => $information['message']];
        }
        //店铺logo
        $information['logo'] = $express_info->shop->logo;
        //商品数量
        $information['goods_num'] = 0;
        foreach ($express_info->memberOrderAttached as $item) {
            $information['goods_num'] += $item->number;
        }

        $information['com'] = Db::name('express')->where(['code' => $information['com']])->value('name');

        //        return json($information);
        return $this->fetch('', [
            'information' => $information
        ]);
    }


    // 退货物流查询
    public function refuend_return()
    {
        $order_id = Request::instance()->param('order_id');
        $express_info = (new \app\mobile\model\MemberRefund())->where('id', $order_id)->find();
        if (!$express_info['tracking'] || !$express_info['tracking_number']) {
            return ['code' => 400, 'message' => '暂未发布物流信息'];
        };

        // 快递100
        $data['customer'] = Cache::get('web_express_customer');
        $data['param'] = json_encode(['com' => $express_info['express_value'], 'num' => $express_info['express_number']]);
        $data["sign"] = strtoupper(md5($data['param'] . Cache::get('web_express_key') . $data['customer']));

        $information = $this->express_post($data, Cache::get('web_express_url'));

        $information['com'] = Db::name('express')->where(['code' => $information['com']])->value('name');

        return $this->fetch('', [
            'information' => $information
        ]);
    }


    // 积分商品物流
    public function integral_record()
    {
        // 获取参数
        $id = Request::instance()->param('order_id');

        // 实例化
        $model = new MemberIntegral();

        // 查出快递参数
        $express_info = $model->where('id',$id)->find();

        if (!$express_info['express_value'] || !$express_info['tracking_number']) {
            return ['code' => 400, 'message' => '暂未发布物流信息'];
        };

        // 快递100
        $data['customer'] = Cache::get('web_express_customer');
        $data['param'] = json_encode(['com' => $express_info['express_value'], 'num' => $express_info['tracking_number']]);
        $data["sign"] = strtoupper(md5($data['param'] . Cache::get('web_express_key') . $data['customer']));

        $information = $this->express_post($data, Cache::get('web_express_url'));

        $information['com'] = Db::name('express')->where(['code' => $information['com']])->value('name');


        return $this->fetch('', [

            'information' => $information
        ]);

    }


    // 积分商品确认收货
    public function confirm_recharge()
    {
        // 获取参数
        $id = Request::instance()->param('order_id');

        // 实例化
        $model = new MemberIntegral();

        // 确认收货
        $operation = $model->save(['status'=>3],['id'=>$id]);

        if ($operation) {
            return ['code'=>200,'message'=>'OK'];
        }else{
            return ['code'=>400,'message'=>'Not Found'];
        }
    }

    /*
     * 快递100 post_curl
     */
    protected function express_post($data, $url)
    {
        $o = "";
        foreach ($data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";        //默认UTF-8编码格式
        }
        // halt($o);
        $post_data = substr($o, 0, -1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //value为0表示直接输出结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $is_success = curl_exec($ch);

        curl_close($ch);
        return json_decode($is_success, true);
    }

    /*
     * 用户端 - 订单确认收货
     * @param  string $Session.member_id          会员ID
     * @param  string $order_number               订单号
     */
    public function order_confirm(Request $request)
    {
        if ($request->isPost()) {
            // 获取参数
            $user_id = Session::get('member_id');
            $order_id = $request->post('order_id');   //主订单id
            $order_number = \app\mobile\model\MemberOrder::where('id', $order_id)->value('shop_order_number');

            // 启动事务
            Db::startTrans();
            try {

                // 更改订单状态
                Db::name('member_order')->where(['id' => $order_id])->update(['status' => '3']);
                // if(Cache::get('web_rebate_percentage') == "Y") {
                // 更改金额参数[会员id,店铺订单号]
                $this->receiving_brokerage($user_id, $order_number);
                // }
                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '确认收货成功'];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙'];
            }
        }

    }

    /*
     * 确认收货时候佣金分配
     */
    protected function receiving_brokerage($user_id, $order_number)
    {

        // 分销返利
        $hierarchy = Db::name('member_distribution')
            ->where(['referrals_id' => $user_id])
            ->order(['level' => 'desc'])
            ->value('hierarchy');

        // 判断是否存在
        if (!empty($hierarchy)) {
            $hierarchy = explode(',', $hierarchy);   // 变成数组
            array_shift($hierarchy);                // 去掉第一个key
            array_pop($hierarchy);                  // 去掉最后一个key
            $hierarchy = array_slice($hierarchy, -3);   // 倒数3个
            rsort($hierarchy);                       // 逆向排序
        }

        // 自己分销佣金
        if (isset($user_id)) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $user_id])
                ->value('brokerage');

            //减少待收益 和 增加佣金余额
            Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('to_yield', $brokerage);
            Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('actual_amount', $brokerage);
        }

        // 一级分销佣金
        if (isset($hierarchy[0])) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $hierarchy[0]])
                ->value('brokerage');

            //减少待收益 和 增加佣金余额
            Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setDec('to_yield', $brokerage);
            Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('actual_amount', $brokerage);

        }

        // 二级分销佣金
        if (isset($hierarchy[1])) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $hierarchy[1]])
                ->value('brokerage');

            //减少待收益 和 增加佣金余额
            Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setDec('to_yield', $brokerage);
            Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('actual_amount', $brokerage);
        }
        //从3级开始截取到最后
        if (count($hierarchy) >= 3) {   //判断至少是有3级的
            $hierarchy = array_slice($hierarchy, 2);
            //获取反馈优惠券的信息
            $coupon = Db::name('coupon')->where(['id' => 1])->find();
            if ($coupon) {
                $ini = [];
                foreach ($hierarchy as $key => $item) {
                    $ini[$key]['member_id'] = $item;
                    $ini[$key]['shop_id'] = $coupon['member_id'];
                    $ini[$key]['coupon_id'] = $coupon['id'];
                    $ini[$key]['title'] = $coupon['title'];
                    $ini[$key]['actual_price'] = $coupon['actual_price'];
                    $ini[$key]['virtual_price'] = $coupon['virtual_price'];
                    $ini[$key]['content'] = $coupon['content'];
                    $ini[$key]['start_time'] = $coupon['start_time'];
                    $ini[$key]['end_time'] = $coupon['end_time'];
                    $ini[$key]['status'] = 2;
                    $ini[$key]['create_time'] = time();
                }
                //批量新增给所有2级后面的会员
                (new MemberCoupon())->allowField(true)->saveAll(array_values($ini));
            }
        }
    }


    /*
     * 用户端 - 订单退款
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     */
    public function return_money()
    {
        if (Request::instance()->isPost()) {
            // 获取参数
            $data = Request::instance()->post();
            $data['member_id'] = Session::get('member_id');

            $data['picArr'] = Request::instance()->post('picArr/a', '');
            $data['order_number'] = \app\mobile\model\MemberOrder::where('id', $data['order_id'])->value('shop_order_number');

            if (empty(Session::get('member_id')) || empty($data['order_id'])) throw new Exception('not Empty');

            $model = new MemberRefund();

            $find = $model->where(['member_id' => Session::get('member_id'), 'id' => $data['order_id']])->value('id');

            if (!empty($find)) return ['code' => 402, 'message' => '该订单已经申请退款,请勿重复申请'];

            if (!empty($data['picArr'])) {
                if ($data['picArr']) {
                    $data['picArr'] = array_map(function ($item) {
                        $item = ['path' => $item];
                        return $item;
                    }, $data['picArr']);
                }
                $data['picArr'] = serialize($data['picArr']);
            }

            //增加会员退货记录
            $result = $model->allowField(true)->save($data);

            if ($result) {
                $status = "";
                if ($data['type'] == 1) {
                    $status = 6;
                } else if ($data['type'] == 2) {
                    $status = 9;
                }

                // 更改状态
                \app\mobile\model\MemberOrder::where(['id' => $data['order_id']])->update(['status' => $status]);

                return ['code' => 200, 'message' => '退换货申请成功,等待审核...',];
            }



            return ['code' => 401, 'message' => '网络繁忙'];
        }
        $order_id = Request::instance()->param('order_id');
        $order_price = db('member_order')->where('id',$order_id)->value('price');
        $status = db('member_order')->where('id',$order_id)->value('status');
        return $this->fetch('',['status' => $status]);

    }

    /*
     * 用户端 - 订单退款记录
     * @param  string $user_id          会员ID
     */
    public function return_money_record(Request $request)
    {
        if ($request->isPost()) {
            // 获取参数
            $user_id = Session::get('member_id');
            $page = $request->post('page');

            $model = new MemberRefund();

            $result['data'] = $model->where(['sun_member_refund.member_id' => $user_id])
                ->with('goodsList,memberOrder')
                ->order(['create_time' => 'desc'])
                ->limit(($page - 1) * 5, 5)
                ->select();
            if ($result['data']) {
                foreach ($result['data'] as $value) {
                    if ($value->memberOrder) {
                        $value->memberOrder->shop;
                    }
                }
            }
            $result['pages'] = ceil(count($model
                    ->where(['sun_member_refund.member_id' => $user_id])
                    ->with('goodsList,memberOrder')
                    ->select()) / 5
            );
            return $result;
        }
        return $this->fetch('');

    }

    /*
     * 用户端 - 订单退款输入运单号
     * @param  string $id               ID
     * @param  string $tracking         物流名称
     * @param  string $tracking_number  物流单号
     */
    public function sent_logistics(Request $request)
    {

        if ($request->isPost()) {
            // 获取参数
            $data = Request::instance()->param();

            if (empty($data['id']) || empty($data['tracking']) || empty($data['tracking_number'])) throw new Exception('not Empty');

            $model = new MemberRefund();

            $find = $model->where(['id' => $data['id'], 'status' => '1'])->value('id');

            if (empty($find)) return ['code' => 402, 'message' => '该订单退款暂未通过同意,请耐心等待'];

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

            if ($result) {

                return ['code' => 200, 'message' => '提交成功'];
            }

            return ['code' => 401, 'message' => '网络繁忙'];
        }
        return $this->fetch('');
    }


    /*
     * 订单状态列表专用数组分组
     *
     * @param object $data 二维数组
     * @param object $obj 对象
     */
    protected function orderGrouping($data, $val, $title, $list, $val2, $title2, $val3, $title3, $val4, $title4, $val5, $title5)
    {

        if (empty($data)) return [];

        $result = array_values(array_reduce($data, function ($value, $key) use ($val, $val2, $val3, $val4, $val5, $title, $title2, $title3, $title4, $title5, $list) {
            $name = $key[$val];
            $name2 = $key[$val2];
            $name3 = $key[$val3];
            $name4 = $key[$val4];
            $name5 = $key[$val5];
            unset($key[$val]);
            $value[$name][$title] = $name;
            $value[$name][$title2] = $name2;
            $value[$name][$title3] = $name3;
            $value[$name][$title4] = $name4;
            $value[$name][$title5] = $name5;
            $value[$name][$list][] = $key;
            return $value;
        }));

        return $result;
    }


    /*
     * 检测订单状态
     */
    public function check_status(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->post();
            $value = \app\mobile\model\MemberOrder::where('id', $data['order_id'])->value('status');
            if ($value == 1) {
                return ['code' => 400, 'message' => '尚未发货!'];
            }
            return ['code' => 200];
        }
    }

    /*
     * 用户端 - 订单退款记录详情
     * @param  string $user_id          会员ID
     * @param  string $order_number     订单号
     */
    public function return_details()
    {

        // 获取参数
        $user_id = Session::get('member_id');
        $order_id = Request::instance()->param('order_id');

        if (empty($user_id) || empty($order_id)) throw new Exception('not Empty');

        $order_info = \app\mobile\model\MemberOrder::where(['id' => $order_id])->field('id,shop_id,shop_order_number')->find();

        $result = MemberRefund::where(['order_number' => $order_info['shop_order_number']])
            ->field('order_number,type,status,amount,cause,explain,create_time,price,refund_time')
            ->find();

        $result['shop_title'] = Shop::where(['member_id' => $order_info['shop_id']])->value('title');

        $data = "";


        return $this->fetch('', [
            'item' => $result,
            'data' => $data
        ]);

    }

    /**
     * 提现页面
     */
    public function withdrawals()
    {
        // 记录提现信息
        if (Request::instance()->isPost()) {
            // 获取会员ID
            $user_id = Session::get('member_id');
            $price = Request::instance()->param('price');
            $account = Request::instance()->param('account');
            $name = Request::instance()->param('name', '');
            $way = Request::instance()->param('way', '');
            // 用户之前余额
            $amount = (new MemberBrokerage())->where(['member_id' => $user_id])->value('actual_amount');

            // 判断提现金额是否充足
            if ($amount < $price) return ['code' => 402, 'message' => '余额不足'];

            // 启动事务
            Db::startTrans();
            try {

                $information = [
                    'member_id'   => $user_id,
                    'type_id'     => 2,
                    'way'         => $way,
                    'account'     => $account,
                    'status'      => 3,
                    'cash'        => $price,
                    'create_time' => time()
                ];


                // 添加成功

                Db::name('cash_withdrawal')->insert($information);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('actual_amount', $price);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_audit', $price);
                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '提现成功'];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙'];
            }
        }

    }

    /**
     * 生成订单号
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }
}